package com.ys.nms.module.business.controller.admin.redData;

import com.ys.nms.module.business.libreApi.devices.LibreNmsDeviceClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class RrdToolReader {
    private final LibreNmsDeviceClient deviceClient;
    private final String rrdBasePath =  "/home/fengli/librenms-master/examples/compose/librenms/rrd";
    public RrdQueryResult queryRrdData(RrdQueryParams params) {
        try {
            if (!validateParams(params)) {
                return new RrdQueryResult("参数验证失败", params);
            }

            String rrdFilePath = buildRrdFilePath(params.getDeviceIp(), params.getRrdFile());
            if (!new File(rrdFilePath).exists()) {
                return new RrdQueryResult("RRD文件不存在: " + rrdFilePath, params);
            }

            List<RrdDataPoint> dataPoints = executeRrdToolFetch(
                    rrdFilePath, params.getStartTime(), params.getEndTime()
            );

            return new RrdQueryResult(dataPoints, params);

        } catch (Exception e) {
            log.error("查询RRD数据时发生错误: {}", e.getMessage(), e);
            return new RrdQueryResult("查询失败: " + e.getMessage(), params);
        }
    }

    public RrdQueryResult queryRrdData(String deviceIp, String rrdFile, String startTime, String endTime) {
        RrdQueryParams params = new RrdQueryParams();
        params.setDeviceIp(deviceIp);
        params.setRrdFile(rrdFile);
        params.setStartTime(startTime);
        params.setEndTime(endTime);
        return queryRrdData(params);
    }

    public List<String> getAvailableRrdFiles(String deviceIp) {
        String devicePath = String.format("%s/%s", rrdBasePath, deviceIp);
        File deviceDir = new File(devicePath);

        if (!deviceDir.exists() || !deviceDir.isDirectory()) {
            log.warn("设备目录不存在: {}", devicePath);
            return List.of();
        }

        File[] rrdFiles = deviceDir.listFiles((dir, name) -> name.endsWith(".rrd"));
        return rrdFiles != null ?
                Arrays.stream(rrdFiles).map(File::getName).sorted().collect(Collectors.toList()) :
                List.of();
    }

    public boolean isDeviceAvailable(String deviceIp) {
        String devicePath = String.format("%s/%s", rrdBasePath, deviceIp);
        return new File(devicePath).exists();
    }

    private boolean validateParams(RrdQueryParams params) {
        if (params.getDeviceIp() == null || params.getDeviceIp().trim().isEmpty()) {
            log.error("设备IP不能为空");
            return false;
        }
        if (params.getRrdFile() == null || params.getRrdFile().trim().isEmpty()) {
            log.error("RRD文件名不能为空");
            return false;
        }
        return true;
    }

    private String buildRrdFilePath(String deviceIp, String rrdFile) {
        String currentUrl = deviceClient.getCurrentUrl();
        System.out.println("读取rrd文件:" + currentUrl);
        return String.format("%s/%s/%s", rrdBasePath, deviceIp, rrdFile);
    }

    private List<RrdDataPoint> executeRrdToolFetch(String rrdFilePath, String start, String end)
            throws Exception {

        List<String> command = Arrays.asList("rrdtool", "fetch", rrdFilePath, "AVERAGE", "--start", start, "--end", end);
        log.debug("执行RRDtool命令: {}", String.join(" ", command));

        Process process = new ProcessBuilder(command).start();
        List<String> outputLines = readProcessOutput(process);

        if (process.waitFor() != 0) {
            throw new Exception("RRDtool命令执行失败");
        }

        return parseRrdOutput(outputLines);
    }

    private List<String> readProcessOutput(Process process) throws Exception {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (!trimmedLine.isEmpty()) {
                    lines.add(trimmedLine);
                }
            }
        }
        return lines;
    }

    private List<RrdDataPoint> parseRrdOutput(List<String> outputLines) {
        return outputLines.stream()
                .filter(line -> !line.startsWith(" ") && !line.contains("timestamp") && !line.isEmpty())
                .map(this::parseDataLine)
                .filter(point -> point != null)
                .collect(Collectors.toList());
    }

    private RrdDataPoint parseDataLine(String line) {
        try {
            String[] parts = line.split(":");
            if (parts.length != 2) {
                log.warn("数据行格式错误: {}", line);
                return null;
            }

            Long timestamp = Long.parseLong(parts[0].trim());
            String valueStr = parts[1].trim();

            Double value = "-nan".equalsIgnoreCase(valueStr) || "nan".equalsIgnoreCase(valueStr) ?
                    Double.NaN : Double.parseDouble(valueStr);

            RrdDataPoint point = new RrdDataPoint();
            point.setTimestamp(timestamp);
            point.setValue(value);
            return point;

        } catch (NumberFormatException e) {
            log.warn("解析数据行失败: {}", line);
            return null;
        }
    }

    public List<RrdDataPoint> getValidDataPoints(RrdQueryResult result) {
        return result.getDataPoints().stream()
                .filter(RrdDataPoint::isValid)
                .collect(Collectors.toList());
    }
}
